[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. import React, { ReactNode, useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import type {
  11. GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { useCurrentGrowiLayoutFluidClassName, useEditorModeClassName } from '~/client/services/layout';
  19. import { PageView } from '~/components/Page/PageView';
  20. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript'; import type { CrowiRequest } from '~/interfaces/crowi-request';
  21. import type { EditorConfig } from '~/interfaces/editor-settings';
  22. import type { IPageGrantData } from '~/interfaces/page';
  23. import type { RendererConfig } from '~/interfaces/services/renderer';
  24. import type { PageModel, PageDocument } from '~/server/models/page';
  25. import type { PageRedirectModel } from '~/server/models/page-redirect';
  26. import {
  27. useCurrentUser,
  28. useIsForbidden, useIsSharedUser,
  29. useIsEnabledStaleNotification, useIsIdenticalPath,
  30. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  31. useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  32. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  33. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPathname,
  34. useIsSlackConfigured, useRendererConfig,
  35. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  36. } from '~/stores/context';
  37. import { useEditingMarkdown } from '~/stores/editor';
  38. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  39. import {
  40. useSWRxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId, useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  41. } from '~/stores/page';
  42. import { useRedirectFrom } from '~/stores/page-redirect';
  43. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  44. import { useSelectedGrant } from '~/stores/ui';
  45. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  46. import loggerFactory from '~/utils/logger';
  47. import { BasicLayout } from '../components/Layout/BasicLayout';
  48. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  49. import type { GrowiSubNavigationSwitcherProps } from '../components/Navbar/GrowiSubNavigationSwitcher';
  50. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  51. import type { NextPageWithLayout } from './_app.page';
  52. import type { CommonProps } from './utils/commons';
  53. import {
  54. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig,
  55. } from './utils/commons';
  56. declare global {
  57. // eslint-disable-next-line vars-on-top, no-var
  58. var globalEmitter: EventEmitter;
  59. }
  60. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  61. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  62. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  63. const GrowiSubNavigationSwitcher = dynamic<GrowiSubNavigationSwitcherProps>(() => import('../components/Navbar/GrowiSubNavigationSwitcher')
  64. .then(mod => mod.GrowiSubNavigationSwitcher), { ssr: false });
  65. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  66. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  67. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  68. const LinkEditModal = dynamic(() => import('../components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  69. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  70. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  71. const logger = loggerFactory('growi:pages:all');
  72. const {
  73. isPermalink: _isPermalink, isTrashPage: _isTrashPage, isCreatablePage,
  74. } = pagePathUtils;
  75. const { removeHeadingSlash } = pathUtils;
  76. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  77. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  78. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  79. {
  80. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  81. return v?.data != null
  82. && v?.data.toObject != null
  83. && v?.meta != null
  84. && isIPageInfoForEntity(v.meta);
  85. },
  86. serialize: (v) => {
  87. return {
  88. data: superjson.stringify(v.data.toObject()),
  89. meta: superjson.stringify(v.meta),
  90. };
  91. },
  92. deserialize: (v) => {
  93. return {
  94. data: superjson.parse(v.data),
  95. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  96. };
  97. },
  98. },
  99. 'IPageToShowRevisionWithMetaTransformer',
  100. );
  101. // GrowiContextualSubNavigation for NOT shared page
  102. type GrowiContextualSubNavigationProps = {
  103. isLinkSharingDisabled: boolean,
  104. }
  105. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  106. const { isLinkSharingDisabled } = props;
  107. const { data: currentPage } = useSWRxCurrentPage();
  108. return (
  109. <div data-testid="grw-contextual-sub-nav">
  110. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  111. </div>
  112. );
  113. };
  114. const PutbackPageModal = (): JSX.Element => {
  115. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  116. return <PutbackPageModal />;
  117. };
  118. type Props = CommonProps & {
  119. pageWithMeta: IPageToShowRevisionWithMeta | null,
  120. // pageUser?: any,
  121. redirectFrom?: string;
  122. // shareLinkId?: string;
  123. isLatestRevision?: boolean,
  124. isIdenticalPathPage?: boolean,
  125. isForbidden: boolean,
  126. isNotFound: boolean,
  127. isNotCreatable: boolean,
  128. // isAbleToDeleteCompletely: boolean,
  129. templateTagData?: string[],
  130. templateBodyData?: string,
  131. isSearchServiceConfigured: boolean,
  132. isSearchServiceReachable: boolean,
  133. isSearchScopeChildrenAsDefault: boolean,
  134. isSlackConfigured: boolean,
  135. // isMailerSetup: boolean,
  136. isAclEnabled: boolean,
  137. // hasSlackConfig: boolean,
  138. drawioUri: string | null,
  139. hackmdUri: string,
  140. noCdn: string,
  141. // highlightJsStyle: string,
  142. isAllReplyShown: boolean,
  143. isContainerFluid: boolean,
  144. editorConfig: EditorConfig,
  145. isEnabledStaleNotification: boolean,
  146. isEnabledAttachTitleHeader: boolean,
  147. // isEnabledLinebreaks: boolean,
  148. // isEnabledLinebreaksInComments: boolean,
  149. adminPreferredIndentSize: number,
  150. isIndentSizeForced: boolean,
  151. disableLinkSharing: boolean,
  152. grantData?: IPageGrantData,
  153. rendererConfig: RendererConfig,
  154. };
  155. const Page: NextPageWithLayout<Props> = (props: Props) => {
  156. // register global EventEmitter
  157. if (isClient() && window.globalEmitter == null) {
  158. window.globalEmitter = new EventEmitter();
  159. }
  160. const router = useRouter();
  161. useCurrentUser(props.currentUser ?? null);
  162. // commons
  163. useEditorConfig(props.editorConfig);
  164. useCsrfToken(props.csrfToken);
  165. // page
  166. useIsContainerFluid(props.isContainerFluid);
  167. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  168. useIsForbidden(props.isForbidden);
  169. useIsNotCreatable(props.isNotCreatable);
  170. useRedirectFrom(props.redirectFrom ?? null);
  171. useIsSharedUser(false); // this page cann't be routed for '/share'
  172. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  173. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  174. useIsSearchPage(false);
  175. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  176. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  177. useIsSearchServiceReachable(props.isSearchServiceReachable);
  178. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  179. useIsSlackConfigured(props.isSlackConfigured);
  180. // useIsMailerSetup(props.isMailerSetup);
  181. useIsAclEnabled(props.isAclEnabled);
  182. // useHasSlackConfig(props.hasSlackConfig);
  183. useHackmdUri(props.hackmdUri);
  184. // useNoCdn(props.noCdn);
  185. useDefaultIndentSize(props.adminPreferredIndentSize);
  186. useIsIndentSizeForced(props.isIndentSizeForced);
  187. useDisableLinkSharing(props.disableLinkSharing);
  188. useRendererConfig(props.rendererConfig);
  189. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  190. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  191. useIsAllReplyShown(props.isAllReplyShown);
  192. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  193. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  194. const { pageWithMeta } = props;
  195. const pageId = pageWithMeta?.data._id;
  196. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  197. const revisionBody = pageWithMeta?.data.revision?.body;
  198. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  199. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  200. useCurrentPathname(props.currentPathname);
  201. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  202. const { mutate: mutateIsNotFound } = useIsNotFound();
  203. const { mutate: mutateCurrentPageId } = useCurrentPageId();
  204. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  205. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  206. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  207. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  208. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  209. const { mutate: mutateRevisionIdHackmdSynced } = useRevisionIdHackmdSynced();
  210. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  211. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  212. useSetupGlobalSocket();
  213. useSetupGlobalSocketForPage(pageId);
  214. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName(pageWithMeta?.data);
  215. const shouldRenderPutbackPageModal = pageWithMeta != null
  216. ? _isTrashPage(pageWithMeta.data.path)
  217. : false;
  218. // sync grant data
  219. useEffect(() => {
  220. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  221. mutateSelectedGrant(grantDataToApply);
  222. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  223. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  224. useEffect(() => {
  225. const decodedURI = decodeURI(window.location.pathname);
  226. if (isClient() && decodedURI !== props.currentPathname) {
  227. const { search, hash } = window.location;
  228. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  229. }
  230. }, [props.currentPathname, router]);
  231. // initialize mutateEditingMarkdown only once per page
  232. // need to include useCurrentPathname not useCurrentPagePath
  233. useEffect(() => {
  234. if (props.currentPathname != null) {
  235. mutateEditingMarkdown(revisionBody);
  236. }
  237. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  238. useEffect(() => {
  239. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  240. mutateRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  241. }, [mutateRemoteRevisionId, mutateRevisionIdHackmdSynced, pageWithMeta?.data.revision?._id, pageWithMeta?.data.revisionHackmdSynced]);
  242. useEffect(() => {
  243. mutateCurrentPageId(pageId ?? null);
  244. }, [mutateCurrentPageId, pageId]);
  245. useEffect(() => {
  246. mutateIsNotFound(props.isNotFound);
  247. }, [mutateIsNotFound, props.isNotFound]);
  248. useEffect(() => {
  249. mutateIsLatestRevision(props.isLatestRevision);
  250. }, [mutateIsLatestRevision, props.isLatestRevision]);
  251. useEffect(() => {
  252. mutateTemplateTagData(props.templateTagData);
  253. }, [props.templateTagData, mutateTemplateTagData]);
  254. useEffect(() => {
  255. mutateTemplateBodyData(props.templateBodyData);
  256. }, [props.templateBodyData, mutateTemplateBodyData]);
  257. const title = generateCustomTitleForPage(props, pagePath);
  258. return (
  259. <>
  260. <Head>
  261. <title>{title}</title>
  262. </Head>
  263. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  264. <header className="py-0 position-relative">
  265. <div id="grw-subnav-container">
  266. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  267. </div>
  268. </header>
  269. <div className="d-edit-none">
  270. <GrowiSubNavigationSwitcher isLinkSharingDisabled={props.disableLinkSharing} />
  271. </div>
  272. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  273. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  274. <DisplaySwitcher
  275. pageView={
  276. <PageView
  277. pagePath={pagePath}
  278. initialPage={pageWithMeta?.data}
  279. rendererConfig={props.rendererConfig}
  280. />
  281. }
  282. />
  283. <PageStatusAlert />
  284. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  285. </div>
  286. </>
  287. );
  288. };
  289. type LayoutProps = Props & {
  290. children?: ReactNode
  291. }
  292. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  293. const className = useEditorModeClassName();
  294. // init sidebar config with UserUISettings and sidebarConfig
  295. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  296. return (
  297. <BasicLayout className={className}>
  298. {children}
  299. </BasicLayout>
  300. );
  301. };
  302. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  303. return (
  304. <>
  305. <GrowiPluginsActivator />
  306. <DrawioViewerScript />
  307. <Layout {...page.props}>
  308. {page}
  309. </Layout>
  310. <UnsavedAlertDialog />
  311. <DescendantsPageListModal />
  312. <DrawioModal />
  313. <HandsontableModal />
  314. <QuestionnaireModalManager />
  315. <TemplateModal />
  316. <LinkEditModal />
  317. </>
  318. );
  319. };
  320. function getPageIdFromPathname(currentPathname: string): string | null {
  321. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  322. }
  323. class MultiplePagesHitsError extends ExtensibleCustomError {
  324. pagePath: string;
  325. constructor(pagePath: string) {
  326. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  327. this.pagePath = pagePath;
  328. }
  329. }
  330. // apply parent page grant fot creating page
  331. async function applyGrantToPage(props: Props, ancestor: any) {
  332. await ancestor.populate('grantedGroup');
  333. const grant = {
  334. grant: ancestor.grant,
  335. };
  336. const grantedGroup = ancestor.grantedGroup ? {
  337. grantedGroup: {
  338. id: ancestor.grantedGroup.id,
  339. name: ancestor.grantedGroup.name,
  340. },
  341. } : {};
  342. props.grantData = Object.assign(grant, grantedGroup);
  343. }
  344. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  345. const { model: mongooseModel } = await import('mongoose');
  346. const req: CrowiRequest = context.req as CrowiRequest;
  347. const { crowi } = req;
  348. const { revisionId } = req.query;
  349. const Page = crowi.model('Page') as PageModel;
  350. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  351. const { pageService } = crowi;
  352. let currentPathname = props.currentPathname;
  353. const pageId = getPageIdFromPathname(currentPathname);
  354. const isPermalink = _isPermalink(currentPathname);
  355. const { user } = req;
  356. if (!isPermalink) {
  357. // check redirects
  358. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  359. if (chains != null) {
  360. // overwrite currentPathname
  361. currentPathname = chains.end.toPath;
  362. props.currentPathname = currentPathname;
  363. // set redirectFrom
  364. props.redirectFrom = chains.start.fromPath;
  365. }
  366. // check whether the specified page path hits to multiple pages
  367. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  368. if (count > 1) {
  369. throw new MultiplePagesHitsError(currentPathname);
  370. }
  371. }
  372. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  373. const page = pageWithMeta?.data as unknown as PageDocument;
  374. // add user to seen users
  375. if (page != null && user != null) {
  376. await page.seen(user);
  377. }
  378. // populate & check if the revision is latest
  379. if (page != null) {
  380. page.initLatestRevisionField(revisionId);
  381. await page.populateDataToShowRevision();
  382. props.isLatestRevision = page.isLatestRevision();
  383. }
  384. if (page == null && user != null) {
  385. const templateData = await Page.findTemplate(props.currentPathname);
  386. if (templateData != null) {
  387. props.templateTagData = templateData.templateTags as string[];
  388. props.templateBodyData = templateData.templateBody as string;
  389. }
  390. // apply pagrent page grant
  391. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  392. if (ancestor != null) {
  393. await applyGrantToPage(props, ancestor);
  394. }
  395. }
  396. props.pageWithMeta = pageWithMeta;
  397. }
  398. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  399. const req: CrowiRequest = context.req as CrowiRequest;
  400. const { crowi } = req;
  401. const Page = crowi.model('Page') as PageModel;
  402. const { currentPathname } = props;
  403. const pageId = getPageIdFromPathname(currentPathname);
  404. const isPermalink = _isPermalink(currentPathname);
  405. const page = props.pageWithMeta?.data;
  406. if (props.isIdenticalPathPage) {
  407. props.isNotCreatable = true;
  408. }
  409. else if (page == null) {
  410. props.isNotFound = true;
  411. props.isNotCreatable = !isCreatablePage(currentPathname);
  412. // check the page is forbidden or just does not exist.
  413. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  414. props.isForbidden = count > 0;
  415. }
  416. else {
  417. props.isNotFound = page.isEmpty;
  418. props.isNotCreatable = false;
  419. props.isForbidden = false;
  420. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  421. if (isPermalink && page.isEmpty) {
  422. props.currentPathname = page.path;
  423. }
  424. // /path/to/page ==> /62a88db47fed8b2d94f30000
  425. if (!isPermalink && !page.isEmpty) {
  426. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  427. if (!isToppage) {
  428. props.currentPathname = `/${page._id}`;
  429. }
  430. }
  431. }
  432. }
  433. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  434. // const req: CrowiRequest = context.req as CrowiRequest;
  435. // const { crowi } = req;
  436. // const UserModel = crowi.model('User');
  437. // if (isUserPage(props.currentPagePath)) {
  438. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  439. // if (user != null) {
  440. // props.pageUser = JSON.stringify(user.toObject());
  441. // }
  442. // }
  443. // }
  444. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  445. const req: CrowiRequest = context.req as CrowiRequest;
  446. const { crowi } = req;
  447. const {
  448. searchService, configManager, aclService,
  449. } = crowi;
  450. props.isSearchServiceConfigured = searchService.isConfigured;
  451. props.isSearchServiceReachable = searchService.isReachable;
  452. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  453. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  454. // props.isMailerSetup = mailService.isMailerSetup;
  455. props.isAclEnabled = aclService.isAclEnabled();
  456. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  457. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  458. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  459. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  460. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  461. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  462. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  463. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  464. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  465. props.editorConfig = {
  466. upload: {
  467. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  468. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  469. },
  470. };
  471. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  472. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  473. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  474. props.rendererConfig = {
  475. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  476. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  477. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  478. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  479. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  480. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  481. // XSS Options
  482. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  483. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  484. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  485. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  486. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  487. };
  488. }
  489. /**
  490. * for Server Side Translations
  491. * @param context
  492. * @param props
  493. * @param namespacesRequired
  494. */
  495. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  496. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  497. props._nextI18Next = nextI18NextConfig._nextI18Next;
  498. }
  499. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  500. const req = context.req as CrowiRequest<IUserHasId & any>;
  501. const { user } = req;
  502. const result = await getServerSideCommonProps(context);
  503. // check for presence
  504. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  505. if (!('props' in result)) {
  506. throw new Error('invalid getSSP result');
  507. }
  508. const props: Props = result.props as Props;
  509. if (props.redirectDestination != null) {
  510. return {
  511. redirect: {
  512. permanent: false,
  513. destination: props.redirectDestination,
  514. },
  515. };
  516. }
  517. if (user != null) {
  518. props.currentUser = user.toObject();
  519. }
  520. try {
  521. await injectPageData(context, props);
  522. }
  523. catch (err) {
  524. if (err instanceof MultiplePagesHitsError) {
  525. props.isIdenticalPathPage = true;
  526. }
  527. else {
  528. throw err;
  529. }
  530. }
  531. await injectRoutingInformation(context, props);
  532. injectServerConfigurations(context, props);
  533. await injectNextI18NextConfigurations(context, props, ['translation']);
  534. return {
  535. props,
  536. };
  537. };
  538. export default Page;